import { _decorator, Component, Animation, Node, Sprite, tween } from 'cc';
import { Loader } from '../tools/LoadManger';
import { EventName, skin_config } from '../manager/AppControll';
import { SoundManager } from '../manager/SoundManger';
import EvtManger from '../tools/EvtManger';
import { GameData, SkinFragment } from '../system/GameData';
const { ccclass, property } = _decorator;

@ccclass('SkinDebris')
export class SkinDebris extends Component {
    @property(Sprite)
    mSpGun: Sprite = null;

    private mNSpeed = 1000;
    private mConfig: skin_config = null;
    private mCount = 0;
    private mEndPoint = null;
    protected onLoad(): void {
        this.InitView();
    }

    start() {

    }

    update(deltaTime: number) {

    }

    InitSkinDebris(config, count, endPoint) {
        this.mConfig = config;
        this.mCount = count;
        this.mEndPoint = endPoint;
        this.node.getComponent(Animation).on(Animation.EventType.FINISHED, this.DoMove, this);
    }

    InitView() {
        Loader.LoadGunImage("mainGunSkin/" + this.mConfig.mainGunSkinRes, (spf) => {
            this.mSpGun.spriteFrame = spf;
            this.node.getComponent(Animation).play();
        });
    }

    DoMove() {
        SoundManager.Instance<SoundManager>().PlayEffect("ui/debrisFly");
        let time = this.mEndPoint.clone().subtract(this.node.position).length() / this.mNSpeed;
        const dropAnimation = tween()
            .to(time, { position: this.mEndPoint.clone().subtract(this.node.position) })
            .call(() => {
                this.AddSkinfragments();
            });
        tween(this.node)
            .then(dropAnimation.clone(this.node))
            .start();
        this.scheduleOnce(() => {
            this.node.destroy();
        }, time + 0.01);
    }

    AddSkinfragments() {
        let isHave = false
        for (let i = 0; i < GameData.playerData.skinFragments.length; i++) {
            let temp: SkinFragment = GameData.playerData.skinFragments[i]
            if (temp.skinId == this.mConfig.skinId) {
                isHave = true;
                GameData.playerData.skinFragments[i].count += this.mCount;
                break;
            }
        }
        if (!isHave) {
            let skinFragment: SkinFragment = {
                skinId: this.mConfig.skinId,
                count: this.mCount,
            }
            GameData.playerData.skinFragments.push(skinFragment);
        }

    }
}


